<template>
  <!-- 项目评估 -->
  <div class="app-container">
    <div class="mainbox">
      <!-- 顶部操作 -->
      <div class="filter-container">
        <el-form ref="filterFormRef" :inline="true" :model="filterForm">
          <el-form-item label="专班名称:" prop="indexName">
            <el-input
              v-model.trim="filterForm.indexName"
              class="filter-item limit"
              style="width: 200px;margin-right:10px"
              maxlength="30"
              clearable
              placeholder="请输入专班名称"
              @keyup.enter.native="$_handleFilter"
            />
          </el-form-item>
          <el-form-item label="专班队长:" prop="userName">
            <el-input
              v-model.trim="filterForm.userName"
              class="filter-item limit"
              style="width: 200px;margin-right:10px"
              maxlength="30"
              clearable
              placeholder="请输入专班队长"
              @keyup.enter.native="$_handleFilter"
            />
          </el-form-item>
        </el-form>
        <div class="flex-1"></div>
        <el-button type="primary" @click="$_handleFilter">查询</el-button>
        <el-button @click="$_handleReset">重置</el-button>
      </div>
      <!-- 表格 -->
      <div class="table-container table-fullscreen">
        <div class="table-opt-container">
          <el-button
            v-permission="['SPECIALCLASSES_ADD_BUTTON']"
            type="primary"
            icon="el-icon-plus"
            @click="handleAdd"
          >
            新增
          </el-button>
          <div class="flex-1" />
          <dt-dialog-column :columns="columns" @queryTable="getList" />
        </div>
        <el-table
          ref="table"
          v-loading="MX_listLoading"
          :data="MX_list"
          border
          highlight-current-row
          :row-key="$_getRowKey"
          style="width: 100%;text-align:center"
          :header-cell-style="MX_headerCellStyle"
        >
          <template slot="empty">
            <p>{{ $store.getters.dataText }}</p>
          </template>
          <el-table-column
            fixed="left"
            type="index"
            label="序号"
            width="70"
            align="center"
            :index="$_tableIndex"
          />
          <el-table-column
            v-for="item in columns"
            :key="item.prop"
            :prop="item.prop"
            :label="item.label"
            :width="item.width"
            :min-width="item.minWidth"
            :formatter="item.formatter"
            align="center"
            show-overflow-tooltip
          />
          <el-table-column
            :key="Math.random()"
            fixed="right"
            label="操作"
            width="240px"
            align="center"
          >
            <template slot-scope="scope">
              <el-button
                size="mini"
                class="tBtn"
                @click="getDetail(scope.row)"
              >详情</el-button>
              <el-button
                v-permission="['SPECIALCLASSES_UPDATE_BUTTON']"
                size="mini"
                class="tBtn"
                @click="handleEdit(scope.row)"
              >修改</el-button>
              <el-button
                v-permission="['SPECIALCLASSES_DEL_BUTTON']"
                size="mini"
                type="danger"
                class="tBtn"
                @click="handleDelete(scope.row[idKeyName])"
              >删除</el-button>
            </template>
          </el-table-column>
        </el-table>
        <!-- 分页器 -->
        <dt-pagination
          v-show="MX_total > 0"
          :total="MX_total"
          :page.sync="MX_pageNav.pageNo"
          :limit.sync="MX_pageNav.pageSize"
          @pagination="getList"
        />
      </div>
      <DialogForm ref="dialogForm" labelWidth="140px" :formDesignList="formDesignList" :otherParams="otherParams">
        <template slot="other">
          <el-form label-width="140px" label-position="left">
            <el-form-item
              required
              label="专班队长"
              :error="!!otherParams.leader || MX_dialogType === 'detail' ? '' : '请选择专班队长'">
              <el-button v-if="MX_dialogType === 'detail'" class="inputDiv">{{otherParams.leaderName || ''}}</el-button>
              <el-button v-else class="inputDiv" @click="openGroupUserPop('leader')">{{otherParams.leaderName || ''}}<i class="el-icon-arrow-right el-icon--right"></i></el-button>
            </el-form-item>
            <el-form-item
              v-for="(v, k) in otherParams.groupIndexUsers" :key="k"
              required
              :label="!k ? '专班成员' : ''"
              :error="!!v.userId || MX_dialogType === 'detail' ? '' : '请选择专班成员'">
                <div style="display: flex;">
                  <el-button v-if="MX_dialogType === 'detail'" class="inputDiv">{{v.userName || ''}}</el-button>
                  <el-button v-else class="inputDiv" @click="openGroupUserPop('cy', k)">{{v.userName || ''}}<i class="el-icon-arrow-right el-icon--right"></i></el-button>
                  <div v-if="MX_dialogType !== 'detail'">
                    <el-button
                      v-if="!k"
                      size="small"
                      class="tBtn"
                      type="primary"
                      @click="addIndexItem()"
                      style="margin-left: 10px;"
                    >添加</el-button>
                    <el-button
                      v-if="!!k"
                      size="small"
                      type="danger"
                      class="tBtn"
                      @click="delIndexItem(k)"
                      style="margin-left: 10px;"
                    >删除</el-button>
                  </div>
                </div>
            </el-form-item>
          </el-form>
        </template>
      </DialogForm>
      <!--      -->
      <dtDialog class="groupUserPop" :title="`选择${chooseType==='cy'?'成员':'队长'}`" :visible.sync="isOpenGroupUserPop" width="900px" @closeDialog="handleClose" :footerSlot="true">
        <GroupUser ref="treeDom" @getGroupUser="getGroupUser" hideCheckBox />
      </dtDialog>
    </div>
  </div>
</template>
<script>
import DialogForm from '@/views/investment/components/DialogForm'
import commonList from "@/utils/mixins/investment/commonList";
import systemApi from "@/api/investment/system";
import FormTemplate from "@/views/investment/components/FormTemplate";
import GroupUser from "@/views/investment/components/GroupUser";
import intservApi from "@/api/investment/intserv";

export default {
  name: 'SpecialClasses',
  components: {
    DialogForm,
    FormTemplate,
    GroupUser
  },
  mixins: [commonList],
  data() {
    return {
      getDetailApi: systemApi.detailZBItem,
      filterForm: {
        indexName: '',
        leaderName: ''
      },
      // 列信息
      columns: [
        { prop: 'groupName', label: `专班名称` },
        { prop: 'leaderName', label: `专班队长` },
        { prop: 'createTime', label: `创建时间`, width: '220px' },
        { prop: 'createUser', label: `创建人`, width: '140px' }
      ],
      formDesignList: [
        { type: 'text', prop: 'groupName', label: `专班名称`, rules: [{ required: true, message: '请输入专班名称', trigger: 'blur' }] },
        { type: 'text', prop: 'groupMobile', label: `联系电话`, rules: [{ required: true, message: '请输入联系电话', trigger: 'blur' }, { pattern: /^(1[3456789]\d{9})$/, message: '请输入有效的联系电话', trigger: 'blur' }] },
        { type: 'textarea', prop: 'groupRemark', label: `专班介绍`, maxlength: 450, autosize: {minRows: 4, maxRows: 10} },
      ],
      idKeyName: 'id',
      otherParams: { leader: '', leaderName: '', groupIndexUsers: [] },
      chooseType: '',
      chooseIndex: null,
      isOpenGroupUserPop: false
    }
  },
  created() {
    this.getList()
  },
  activated() {
    this.$_resetTableLayout()
  },
  methods: {
    openGroupUserPop(type, index){
      if (type === 'cy') this.chooseIndex = index
      this.chooseType = type
      this.isOpenGroupUserPop = true
      this.$nextTick(() => {
        this.$refs.treeDom.initTree()
      })
    },
    getGroupUser(users){
      let flag = true
      if (!!users){
        if (this.chooseType === 'cy'){
          if (users.userId === this.otherParams.leader || !!this.otherParams.groupIndexUsers.some(v => v.userId === users.userId)){
            flag = false
            this.$message.error(`当前选择用户已被选为队长 / 成员！`)
          }else{
            Object.assign(this.otherParams.groupIndexUsers[this.chooseIndex], {
              userId: users.userId, userName: users.realName
            })
          }
        }else{
          if (!!this.otherParams.groupIndexUsers.some(v => v.userId === users.userId)){
            flag = false
            this.$message.error(`当前选择用户已被选为成员！`)
          }else{
            Object.assign(this.otherParams, {
              leader: users.userId, leaderName: users.realName
            })
          }
        }
      }
      if (!!flag) this.handleClose()
    },
    handleClose(){
      this.chooseType = ''
      this.chooseIndex = null
      this.isOpenGroupUserPop = false
    },
    // 获取页面列表
    getList() {
      this.$_getList(systemApi.getZBList,{
        ...this.filterForm,
        ...this.MX_pageNav
      })
    },
    setCyForm(res){
      this.$set(this.otherParams, 'leader', res.leader || '')
      this.$set(this.otherParams, 'leaderName', res.leaderName || '')
      this.$set(this.otherParams, 'groupIndexUsers', res.groupIndexUsers || [])
    },
    getDetail(data){
      this.$_handleDetail(data, this.getDetailApi, this.idKeyName, (res) => {
        this.setCyForm(res)
      }, true)
    },
    // 编辑按钮
    handleEdit(data) {
      this.$_handleDetail(data, this.getDetailApi, this.idKeyName, (res) => {
        this.setCyForm(res)
        this.$refs.dialogForm.open('update', systemApi.updateZBItem, res || this.MX_applicationMsg)
      })
    },
    // 添加按钮
    handleAdd() {
      this.otherParams = { leader: '', leaderName: '', groupIndexUsers: [{"id": '',
          "indexId": '',
          "userId": '',
          "userName": ''
      }] }
      this.$refs.dialogForm.open('add', systemApi.addZBItem)
    },
    // 删除按钮
    handleDelete(id) {
      this.$_handleDelete(systemApi.delZBItem, id, `${this.idKeyName}`)
    },
    addIndexItem(){
      this.otherParams.groupIndexUsers.push({
        "id": '',
        "indexId": '',
        "userId": '',
        "userName": ''
      });
    },
    delIndexItem(index){
      if (this.otherParams.groupIndexUsers.length >= 2){
        this.otherParams.groupIndexUsers.splice(index, 1);
      }else{
        this.$message.error(`至少选择一名成员！`)
      }
    },
    otherParamsCheck(){
      let valid = !!this.otherParams.leader
      this.otherParams.groupIndexUsers.map(v => {
        if (!v.userId) valid = false
      })
      // if (!valid){
      //   this.$message.error(`请选择队长 / 成员！`)
      // }
      return !!valid
    }
  }
}
</script>

<style lang="scss" scoped>
.tBtn{
  margin-top: 3px;
  margin-bottom: 3px;
}
.groupUserPop{
  ::v-deep .el-dialog__body{
    padding-top: 0;
    padding-bottom: 0;
  }
}
</style>
